// composables/useServerRequest.ts
import { useFetch, type UseFetchOptions } from "#app";
import userStore from "~/stores/user";
function isArray(str: unknown) {
  return Object.prototype.toString.call(str) === "[object Array]";
}

let messageErrorNumber = 0;
function messageError(message: string) {
  if (messageErrorNumber <= 2) {
    messageErrorNumber++;
    naiveui.message.error(message, {
      onLeave() {
        messageErrorNumber--;
      },
    });
  }
}
// 提示登录失效需要登录
let signInPrompts = false;
function signInPromptDialog() {
  if (signInPrompts) return;
  signInPrompts = true;
  naiveui.dialog.warning({
    title: "警告",
    content: "登录失效，请重新登录",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      navigateTo(`/login`);
    },
    onNegativeClick: () => {},
    onClose: () => {
      signInPrompts = false;
    },
  });
}

interface returnClass<T> {
  code: number;
  data: T;
  message: string;
}

export const useServerRequest = async <T = unknown>(
  url: string,
  opts: UseFetchOptions<T, unknown>
) => {
  const user = userStore();
  let token = user.token;

  if (!token) {
    const userInfo = localStorage.getItem("user");
    if (userInfo) token = JSON.parse(userInfo).token;
    // if (!token) {
    //   navigateTo(`/login`);
    // }
  }
  const runtimeConfig = useRuntimeConfig();

  const defaultOptions: UseFetchOptions<unknown> = {
    baseURL: runtimeConfig.public.baseUrl,
    onRequest({ options }) {
      // 设置请求头
      options.headers = (options.headers || {}) as { [key: string]: string };
      if (token) {
        options.headers.Authorization = "Bearer " + token;
      }
    },
    onRequestError() {
      // 处理请求错误
      process.client && messageError("服务器链接失败!");
    },
    async onResponse({ response }) {
      // 处理响应数据
      if (+response.status === 200) {
        if (opts.method === "GET") return;
        let message = "";
        switch (opts.method) {
          case "POST":
            message = "操作成功";
            break;
          case "PATCH":
            message = "修改成功";
            break;
          case "DELETE":
            message = "删除成功";
            break;
          default:
            break;
        }
        process.client && naiveui.message.success(message);
        return;
      }
      if (+response.status === 401) {
        user.token = "";
        user.userInfo = null;
        // process.client && messageError("登录失效，请重新登录");
        process.client && signInPromptDialog();
      }
      if (+response.status === 403) {
        process.client &&
          messageError(response._data.message || "无此操作权限，请联系管理员");
        return;
      }
      if (+response._data.code !== 0) {
        process.client && messageError(response._data.message || "onResponse");
      } else {
        process.client &&
          naiveui.message.success(response._data.message || "onResponse");
      }
    },
    onResponseError({ request, response, options }) {
      // 处理响应错误
      console.log("处理响应错误onResponseError");
      process.client &&
        messageError(
          isArray(response._data.message)
            ? response._data.message[0]
            : response._data.message || "onResponseError"
        );
    },
  };
  await nextTick();
  const res = await useFetch<returnClass<T>>(url, {
    ...defaultOptions,
    watch: false,
    ...opts,
  } as any);
  return (
    res.data.value ??
    <returnClass<T>>{
      code: -1,
      data: null,
      message: "未知错误",
    }
  );
};
